package sit.mycatalog.web.mbean;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sit.mycatalog.ejb.sess.SysuserSess;
import sit.mycatalog.jpa.Sysuser;
import sit.mycatalog.util.SessLookup;
import sit.mycatalog.web.util.AbstractMBean;

public class LoginBean extends AbstractMBean {
	private String userid;
	private String pwd;
	private Boolean loginpass;
	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Boolean getLoginpass() {
		return loginpass;
	}
	public void setLoginpass(Boolean loginpass) {
		this.loginpass = loginpass;
	}
	
	@PostConstruct
	public void init() {
		loginpass = new Boolean(false);
	}
	
	public void doLogin(ActionEvent event) {
		try {
			HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
			HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
			
			SysuserSess sessSysuser = SessLookup.getSysuserSess();
			Sysuser sysuser = sessSysuser.getSysuser(userid);
			
			if(userid.equals("")) {
				message("Please Enter User");
				this.loginpass = false;
				this.userid = null;
				this.pwd = null;
			} else if(sysuser == null || (!sysuser.isCheck())) {
				message("User Not Found");
				this.loginpass = false;
				this.userid = null;
				this.pwd = null;
			} else if(this.pwd.equals("")) {
				message("Please Enter Password");
				this.loginpass = false;
//				this.userid = null;
//				this.pwd = null;
			} else if((sysuser.getPwd() != null) && (!sysuser.getPwd().equals(pwd))) {
				message("Incorrect Password");
				this.loginpass = false;
//				this.userid = null;
				this.pwd = null;
			} else {
				this.loginpass = true;
				this.userid = sysuser.getUsrid();
				
				response.sendRedirect(request.getContextPath() + "/admin/admin.jsf");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doLogout(ActionEvent event) {
		System.out.println("doLogout");
		this.loginpass = new Boolean(false);
	}
}
